# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# 添加所需的运行库
from operator import truediv
import requests
import json
import hmac
import urllib
import time
import base64
import hashlib
import sys


class DingTalkMsg:
    def __init__(self, webhook_url, secret):
        self.webhook_url = webhook_url
        self.secret = secret

    # 加签
    def signatureUrl(self, webhook_url,secret):
        # 生成当前时间戳，单位是毫秒，与请求调用时间误差不能超过1小时
        timestamp = str(round(time.time() * 1000))
        # 修改编码格式为utf-8
        secret_enc = secret.encode('utf-8')
        # 将timestamp和secret合并
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        # 修改编码格式为utf-8
        string_to_sign_enc = string_to_sign.encode('utf-8')
        # 将字段进行加密，加密类型采用sha256
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        # 生成请求的URL，WebHook地址
        Post_Url = ("%s&timestamp=%s&sign=%s" % (webhook_url, timestamp, sign))
        return Post_Url
    # 发送消息
    def dingMessage(self, Post_Url,Content,People):
        # 构建请求头部
        header = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"
        }
        # 构建请求数据
        message ={
            "msgtype": "text",
            "text": {
                "content": Content
            },
            "at": {
                # "atMobiles":[
                #     "13510236914",
                # ],
                "isAtAll": People
            }
        }
        # 对请求的数据进行json封装、定义头部文件并发送请求
        info = requests.post(url=Post_Url,data=json.dumps(message),headers=header)
        # 判断是否发送成功
        if json.loads(info.text)['errmsg'] == "ok":
            print("发送成功!")
            return True
        else:
            print(json.loads(info.text))
            return False
        
    def sendMsg(self, msg, isAtAll = False):
        postUrl = self.signatureUrl(self.webhook_url, self.secret)
        self.dingMessage(postUrl, msg, isAtAll)

# 使用示例
if __name__=="__main__":
    webhookUrl = "https://oapi.dingtalk.com/robot/send?access_token=4d014f6db22b05e064b08d5bba7c50be8e7743aa3dbf5378da3d65e5a8f1a528"
    secret = "SECd7b84fe3c9c5b43f1c30a78ca9aceac91390ee2d44f8d1e64b745310b008ed66"
    content = sys.argv[1]
    people = sys.argv[2]
    ding = DingTalkMsg(webhookUrl, secret)
    ding.sendMsg(content, people)